package com.vogue.supplymall.shop.common;

import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.shop.domain.model.Administrativearea;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * The type Code transform utils.
 * 根据区域省市的code取出名称
 *
 * @aouthor: zhangliang
 * @date: Create in 2017-12-25
 */
@Component
public class CodeTransformUtils {
    @Resource
    private IMemUtils iMemUtils;

    private List<Administrativearea> areas = new ArrayList<>();
    private List<Administrativearea> citys = new ArrayList<>();

    /**
     * Gets area name.
     * 根据省的国标码查询对应的区域和省的名称
     *
     * @param province the area code
     * @return the area name
     */
    public Map<String, String> getAreaName(String province) {
        Map map = new HashMap<String, String>();
        for (Administrativearea area : getAreas()) {
            if (area.getId().toString().equals(province)) {
                map.put("areaCode", area.getAreacode());
                map.put("area", area.getAreaname());
                map.put("provinceCode", area.getId());
                map.put("province", area.getName());
            }
        }
        return map;
    }

    /**
     * Gets city name.
     * 返回城市代码对应的名称
     *
     * @param city the city
     * @return the city name
     */
    public String getCityName(String city) {
        List<String> arealst = getCitys()
                .parallelStream()
                .filter((area) -> area.getId().toString().equals(city))
                .map(Administrativearea::getName)
                .collect(Collectors.toList());
        return arealst.size() > 0 ? arealst.get(0) : "";
    }

    private List<Administrativearea> getAreas() {
        if (areas.size() == 0) {
            areas = iMemUtils.getArea(ConstantBean.AREA_LEVEL_2);
        }
        return areas;
    }

    private List<Administrativearea> getCitys() {
        if (citys.size() == 0) {
            citys = iMemUtils.getArea(ConstantBean.AREA_LEVEL_3);
        }
        return citys;
    }

    public List<Map<String, Object>> searchArea(List<Map<String, Object>> shops) {
        for (Map<String, Object> shop : shops) {
            if (null != shop.get("province") && null != shop.get("city")) {
                Map<String, String> areaMap = getAreaName(shop.get("province").toString());
                shop.put("area", areaMap.get("area"));
                shop.put("province", areaMap.get("province"));
                shop.put("city", getCityName(shop.get("city").toString()));
            }
        }
        return shops;
    }
}
